package com.jf.blog_jf04.controller;

import com.jf.blog_jf04.bean.Userinfo;
import com.jf.blog_jf04.data.dto.UserinfoDto;
import com.jf.blog_jf04.data.ov.ForgetOV;
import com.jf.blog_jf04.data.ov.LoginOV;
import com.jf.blog_jf04.data.ov.RegisterOV;
import com.jf.blog_jf04.service.KaptchaService;
import com.jf.blog_jf04.service.MessageService;
import com.jf.blog_jf04.service.UserinfoService;
import com.jf.blog_jf04.utils.BeanConvertUtils;
import com.jf.blog_jf04.utils.LoginUtils;
import com.jf.blog_jf04.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.UUID;

@RestController
@Api(tags = "通用接口")
public class BaseController {
    @Autowired
    private KaptchaService kaptchaService;
    @Autowired
    private UserinfoService userinfoService;
    @Autowired
    private MessageService messageService;
    @Value("${filepath}")
    private String filepath;


    @GetMapping("/kaptcha.jpg")
    @ApiOperation("生成图片验证码")
    public void kaptcha(@ApiParam(value = "唯一标识", required = true) @RequestParam String uuid, HttpServletResponse response) throws IOException {
        response.setDateHeader("Expires", 0L);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        BufferedImage bi = kaptchaService.createKaptcha(uuid);// 获取验证码图片
        ServletOutputStream out = response.getOutputStream();
        /*禁用缓存，可以解决部分同学电脑因为权限问题导致的500错误*/
        ImageIO.setUseCache(false);
        ImageIO.write(bi, "jpg", out);
    }

    @ApiOperation("后台登录")
    @PostMapping("/login")
    public R login(@RequestBody LoginOV form) {
        return userinfoService.login(form);
    }

    @GetMapping("/login/info")
    @ApiOperation("登录用户信息")
    public R info() {
        Userinfo userinfo = LoginUtils.getLoginUserinfo();
        return R.success(BeanConvertUtils.copyBean(userinfo, UserinfoDto.class));
    }

    @PostMapping("/logout")
    @ApiOperation("退出登录")
    public R logout() {
        LoginUtils.logout();
        return R.success();
    }

    @PostMapping("/upload")
    @ApiOperation("上传文件")
    public R upload(@ApiParam(value = "上传的文件", required = true) @RequestParam MultipartFile file, @ApiParam("文件所属模块") @RequestParam(required = false) String type) {
        if (file == null) {
            return R.error("上传文件为空");
        }
        if (!StringUtils.hasText(type) || "null".equals(type)) {
            type = "";
        }
        /*获取文件原名称*/
        String originalFilename = file.getOriginalFilename();
        /*获取文件格式后缀*/
        /*断言*/
        assert originalFilename != null;
        String[] ofs = originalFilename.split("\\.");
        String ext = ofs[ofs.length - 1];
        /*生成新文件名*/
        String filename = UUID.randomUUID() + "." + ext;
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int date = calendar.get(Calendar.DATE);

        String datePath = year + "/" + (month < 10 ? "0" + month : month) + "/" + (date < 10 ? "0" + date : date) + "/";
        /*文件路径*/
        String path = "images/" + datePath + type + "/";
        /*验证文件夹是否需要创建*/
        File uploadFile = new File(filepath + path);
        if (!uploadFile.exists()) {
            uploadFile.mkdirs();
        }
        /*存储图片*/
        try {
            file.transferTo(new File(uploadFile, filename));
        } catch (IOException e) {
            return R.error(e.getMessage());
        }
        String jsonFilename = "/images/" + datePath + type + "/" + filename;
        return R.success().put("filename", jsonFilename);
    }

    @PostMapping("/register/send/{phone}")
    @ApiOperation("注册时短信")
    public R registerSend(@ApiParam("手机号") @PathVariable String phone) {
        return messageService.registerSend(phone);
    }

    @PostMapping("/forget/send/{phone}")
    @ApiOperation("忘记密码时短信")
    public R forgetSend(@ApiParam("手机号") @PathVariable String phone) {
        return messageService.forgetSend(phone);
    }


    @PostMapping("/register")
    @ApiOperation("注册用户")
    public R register(@RequestBody RegisterOV form) {
        userinfoService.register(form);
        return R.success();
    }

    @PostMapping("/forget")
    @ApiOperation("忘记密码")
    public R forget(@RequestBody ForgetOV form) {
        userinfoService.forget(form);
        return R.success();
    }

}
